package com.ugoodtech.mdcc.web.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.VstarUserKpiReport.VstarUserKpiReport;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.CoreWeekServiceReportService;
import com.ugoodtech.mdcc.core.service.WechatService;
import com.ugoodtech.mdcc.core.utils.AnswerOtherUtil;
import com.ugoodtech.mdcc.core.utils.ArrayStringUtil;
import com.ugoodtech.mdcc.core.utils.DateUtil;
import com.ugoodtech.mdcc.core.utils.ValidateUtil;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.LabelValue;
import com.ugoodtech.mdcc.web.dto.UserProfileResponse;
import com.ugoodtech.mdcc.web.service.AliSmsProvider;
import com.ugoodtech.mdcc.web.service.ExportReportService;
import com.ugoodtech.mdcc.web.service.UserLogService;
import com.ugoodtech.mdcc.web.service.WeekServiceReportService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(description = "技术人员kpi")
@RestController
@RequestMapping("/weekServiceReport")
public class WeekServiceReportServiceController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(WeekServiceReportServiceController.class);

    @Autowired
    private WeekServiceReportService weekServiceReportService;

    @Autowired
    private ModuleAuthorityRepository moduleAuthorityRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ExportReportService exportReportService;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private AliSmsProvider aliSmsProvider;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserLogService userLogService;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private ReportRedDotRepository reportRedDotRepository;

    @Autowired
    private ServiceReportRecorderRepository serviceReportRecorderRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private ServiceReportHistoricalRecorderRepository serviceReportHistoricalRecorderRepository;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private AutoMessageTimeRepository autoMessageTimeRepository;

    @Autowired
    private CoreWeekServiceReportService coreWeekServiceReportService;

    @ApiOperation("获得技术人员kpi报告--改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getWeekReport", method = RequestMethod.GET)
    public com.ugoodtech.mdcc.core.dto.JsonResponse getWeekReport(@ApiParam("登陆用户ID") @RequestParam(value = "loginUserId") Long loginUserId,
                                                                  @ApiParam("省份") @RequestParam(value = "provinces", required = false) String provinces,
                                                                  @ApiParam("品牌") @RequestParam(value = "brandname", required = false) String brandname,
                                                                  @ApiParam("维修站类型") @RequestParam(value = "category", required = false) String category,
//                                      @ApiParam("维修站名称") @RequestParam(value = "name", required = false) String name,
                                                                  @ApiParam("服务开始时间") @RequestParam(value = "serviceStartTime", required = false) Long serviceStartTime,
                                                                  @ApiParam("服务结束时间") @RequestParam(value = "serviceEndTime", required = false) Long serviceEndTime,
                                                                  @ApiParam("开始时间") @RequestParam(value = "startTime", required = false) Long startTime,
                                                                  @ApiParam("结束时间") @RequestParam(value = "endTime", required = false) Long endTime,
                                                                  @ApiParam("服务项目") @RequestParam(value = "serviceType", required = false) Long serviceType,
//                                      @ApiParam("服务次数") @RequestParam(value = "serviceNum", required = false) Integer serviceNum,
//                                      @ApiParam("技术人员姓名") @RequestParam(value = "userName", required = false) String userName
                                                                  @ApiParam("技术人员姓名") @RequestParam(value = "userName", required = false) String userName,
                                                                  @ApiParam("维修站ID") @RequestParam(value = "stationName", required = false) String stationName,
                                                                  @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) Long customerStat,
                                                                  @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) Long customerType,
                                                                  @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String patintBrand,
                                                                  @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition,
                                                                  @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                                                                  @ApiParam("是否有待跟进") @RequestParam(value = "isFollowUp", required = false) Boolean isFollowUp,
                                                                  @ApiParam("部门ID") @RequestParam(value = "departmentId", required = false) Long departmentId,
                                                                  @ApiParam("是否填写满意度报告") @RequestParam(value = "isCustomer", required = false) Boolean isCustomer,
                                                                  @ApiParam("满意度打分") @RequestParam(value = "score", required = false) String score,
                                                                  Pageable pageable) {
        isUserLogin();
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return com.ugoodtech.mdcc.core.dto.JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
//        ModuleAuthority moduleAuthority = moduleAuthorityRepository.findByName(Constants.REPORT_STATISTICS_PC);
//        boolean tf = user.getAuthorities().contains(moduleAuthority);
//        if (tf == false) {
//            return JsonResponse.errorResponseWithError("抱歉", "没有权限查看报告统计（PC）");
//        }
//        if (userId == null || userId == 0) {
//            return JsonResponse.successResponseWithData("");
//        }
        return coreWeekServiceReportService.statWeekReport(user, userName, stationName, provinces, brandname, category, serviceStartTime, serviceEndTime, isFollowUp, isCustomer, score, serviceType, startTime, endTime, departmentId);
    }


    @ApiOperation("模糊搜索维修站")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = UserProfileResponse.class)
    })
    @RequestMapping(value = "/findOneStation", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse findOneStation(@ApiParam("省份") @RequestParam(value = "province", required = false) String province,
                                       @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                       @ApiParam("维修站名称") @RequestParam(value = "userName", required = false) String stationName) {
        isUserLogin();
        QStation qStation = QStation.station;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStation.deleted.eq(false));
        builder.and(qStation.enabled.eq(true));
        builder.and(qStation.checkStation.eq(true));
        builder.and(qStation.user.isNotNull());
        builder.and(qStation.province.isNotNull());
        builder.and(qStation.city.isNotNull());
        builder.and(qStation.contact.isNotNull());
        if (StringUtils.isNotEmpty(city)) {
            builder.and(qStation.city.eq(city));
        }
        if (StringUtils.isNotEmpty(province)) {
            builder.and(qStation.province.eq(province));
        }
        builder.and(qStation.name.like("%" + stationName + "%"));
        List<Station> stationList = (List<Station>) stationRepository.findAll(builder);
        List<LabelValue> labelValues = new ArrayList<>();
        if (null != stationList) {
            labelValues = toStationLableValue(stationList);
        }
        return JsonResponse.successResponseWithData(labelValues);
    }

    private List<LabelValue> toStationLableValue(List<Station> stationList) {
        List<LabelValue> labelValues = new ArrayList<>();
        for (Station station : stationList) {
            LabelValue labelValue = new LabelValue(station.getName(), station.getId() + "");
            labelValues.add(labelValue);
        }
        return labelValues;
    }


    @ApiOperation("模糊搜索用户")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = UserProfileResponse.class)
    })
    @RequestMapping(value = "/findOneUser", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse findOneUser(@ApiParam("省份") @RequestParam(value = "province", required = false) String province,
                                    @ApiParam("用户名名称") @RequestParam(value = "userName", required = false) String userName) {
        isUserLogin();
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        if (StringUtils.isNotEmpty(userName)) {
            builder.and(qUserProfile.realName.like("%" + userName + "%"));
        }
        if (StringUtils.isNotEmpty(province)) {
            builder.and(qUserProfile.nationList.any().province.eq(province));
        }
        List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
        List<LabelValue> labelValues = new ArrayList<>();
        if (null != userProfileList) {
            labelValues = toLableValue(userProfileList);
        }
        return JsonResponse.successResponseWithData(labelValues);
    }

    private List<LabelValue> toLableValue(List<UserProfile> userProfileList) {
        List<LabelValue> labelValues = new ArrayList<>();
        for (UserProfile userProfile : userProfileList) {
            LabelValue labelValue = new LabelValue(userProfile.getRealName(), userProfile.getUser().getId() + "");
            labelValues.add(labelValue);
        }
        return labelValues;
    }

    @ApiOperation("导出kpi表格数据")
    @RequestMapping(value = "getKpiResponseOut", method = RequestMethod.POST)
    public JsonResponse getKpiResponseOut(@ApiParam("登陆用户ID") @RequestParam(value = "loginUserId") Long loginUserId, HttpServletRequest request,
                                          HttpServletResponse response,
                                          @ApiParam("省份") @RequestParam(value = "provinces", required = false) String provinces,
                                          @ApiParam("品牌") @RequestParam(value = "brandname", required = false) String brandname,
                                          @ApiParam("维修站类型") @RequestParam(value = "category", required = false) String category,
//                                      @ApiParam("维修站名称") @RequestParam(value = "name", required = false) String name,
                                          @ApiParam("服务开始时间") @RequestParam(value = "serviceStartTime", required = false) Long serviceStartTime,
                                          @ApiParam("服务结束时间") @RequestParam(value = "serviceEndTime", required = false) Long serviceEndTime,
                                          @ApiParam("开始时间") @RequestParam(value = "startTime", required = false) Long startTime,
                                          @ApiParam("结束时间") @RequestParam(value = "endTime", required = false) Long endTime,
                                          @ApiParam("服务项目") @RequestParam(value = "serviceType", required = false) Long serviceType,
//                                      @ApiParam("服务次数") @RequestParam(value = "serviceNum", required = false) Integer serviceNum,
//                                      @ApiParam("技术人员姓名") @RequestParam(value = "userName", required = false) String userName
                                          @ApiParam("技术人员姓名") @RequestParam(value = "userName", required = false) String userName,
                                          @ApiParam("维修站ID") @RequestParam(value = "stationName", required = false) String stationName,
                                          @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) Long customerStat,
                                          @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) Long customerType,
                                          @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String patintBrand,
                                          @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition,
                                          @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                                          @ApiParam("部门ID") @RequestParam(value = "departmentId", required = false) Long departmentId)
            throws Exception {
        isUserLogin();
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
//        ModuleAuthority moduleAuthority = moduleAuthorityRepository.findByName(Constants.REPORT_STATISTICS_PC);
//        boolean tf = user.getAuthorities().contains(moduleAuthority);
//        if (tf == false) {
//            return JsonResponse.errorResponseWithError("抱歉", "没有权限查看报告统计（PC）");
//        }
        System.out.println(request.getSession().getServletContext().getRealPath(""));
        String templetPath = request.getSession().getServletContext().getRealPath("");
        VstarUserKpiReport vstarUserKpiReport = (VstarUserKpiReport) getWeekReport(loginUserId, provinces, brandname, category, serviceStartTime, startTime, endTime, serviceEndTime, serviceType, userName, stationName,
                customerStat, customerType, patintBrand, productPosition, stationNum, null, departmentId, null, null, null).getData();
        String filePath = exportReportService.genWeekKpiReport(vstarUserKpiReport, templetPath);

        userLogService.addUserLog(this.getCurrentUser(), null,
                LogConstants.operate_type_send_export,
                LogConstants.business_type_regular_report, null, null);
        filePath = Constants.v_starServiceUrl + filePath;
//        filePath = "http://116.62.64.140:51002" + filePath;
        return JsonResponse.successResponseWithData(filePath);
    }


    @ApiOperation("管理员处理常规报告--发送短信")
    @RequestMapping(value = "manageSendSms", method = RequestMethod.GET)
    public JsonResponse manageSendSms(@ApiParam("登陆用户ID") @RequestParam(value = "loginUserId") Long loginUserId,
                                      @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId,
                                      @ApiParam("处理内容") @RequestParam(value = "note") String note,
                                      @ApiParam("用户ID") @RequestParam(value = "userIds") String userIds) {
        isUserLogin();
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
        String manageUserRealName = userProfileRepository.findByUserId(user.getId()).getRealName();
        if (reportId == null || reportId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "报告ID数据异常");
        }
        if (StringUtils.isEmpty(note.trim())) {
            return JsonResponse.errorResponseWithError("抱歉", "请输入正确的内容，内容不能为空");
        }
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null || !stationReport.getCategory().equals(Constants.SERVICE_REPORT)) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该报告或此报告不是常规报告");
        }
        User nameUser = stationReport.getUser();
        if (nameUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告的创建人");
        }
        UserProfile userProfile = userProfileRepository.findByUserId(nameUser.getId());
        if (userProfile == null || StringUtils.isEmpty(userProfile.getRealName())) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告的创建人信息");
        }
        Station station = stationReport.getStation();
        if (station == null || StringUtils.isEmpty(station.getName())) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告的维修站");
        }
        if (StringUtils.isEmpty(stationReport.getServiceTypAnswerIds())) {
            return JsonResponse.errorResponseWithError("抱歉", "此报告数据异常，没有服务项目");
        }
        String[] ids = userIds.split(",");
        StringBuffer userBuffer = new StringBuffer("");
        List<User> userList = new ArrayList<>();
        for (String id : ids) {
            if (StringUtils.isNotEmpty(id)) {
                UserProfile telephoneUser = userProfileRepository.findByUserId(Long.valueOf(id));
                if (telephoneUser != null && StringUtils.isNotEmpty(telephoneUser.getTelephone())) {
                    userBuffer.append(telephoneUser.getTelephone() + ",");
                    userList.add(telephoneUser.getUser());
                }
            }
        }

        String[] service = stationReport.getServiceTypAnswerIds().split(",");
        StringBuffer stringBuffer = new StringBuffer("");
        for (String id : service) {
            if (id.equals("191")) {
                stringBuffer.append("漆星服务");
            } else {
                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                if (answerOption != null && StringUtils.isNotEmpty(answerOption.getName())) {
                    stringBuffer.append(answerOption.getName() + ",");
                }
            }
        }
        String serviceStr = stringBuffer.toString();
        if (!serviceStr.equals("漆星服务")) {
            serviceStr = serviceStr.substring(0, serviceStr.length() - 1);
            if (serviceStr.indexOf("车间改善") != -1) {
                serviceStr = "车间改善";
            }
        }

        /**
         * 获取报告状态
         */
        String reportType = "";
        StationRegularServiceReport questionAnswer = stationRegularServiceReportRepository.selectQuestionOther(reportId, 156L);
        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(questionAnswer.getAnswerId()));
        if (answerOption != null && StringUtils.isNotEmpty(answerOption.getName())) {
            reportType = answerOption.getName();
        }

        /**
         * 获取跟进部门
         */
        StringBuffer departmentBuffer = new StringBuffer("");
        String departmentIds = stationReport.getDeparmentIds();
        if (StringUtils.isNotEmpty(departmentIds)) {
            for (String id : departmentIds.split(",")) {
                Department department = departmentRepository.findOne(Long.valueOf(id));
                if (null != department && StringUtils.isNotEmpty(department.getTotalName())) {
                    departmentBuffer.append(department.getTotalName() + "、");
                }
            }
        }


        String realName = userProfile.getRealName();
        String stationName = station.getName();
        try {
            logger.info("发送的手机号码为：" + userBuffer.toString());
            logger.info("创建报告者：" + realName);
            logger.info("维修站名称:" + stationName);
            logger.info("服务项目为:" + serviceStr);

            SendSmsResponse sendSmsResponse = aliSmsProvider.sendCustomerMsg(userBuffer.toString(), realName, stationName,
                    serviceStr, reportType);

            logger.info("发送状态为：{}", sendSmsResponse.getCode());
            logger.info("发送成功");
            logger.info("<<<<<<<<<<<<<<<<<<开始推送微信>>>>>>>>>>>>>>>>>");
            addSendSmsLog(user, realName + "有一份在" + stationName + "进行" + serviceStr + "的常规服务报告，存在注意事项" + note + "，请留意。", reportId, sendSmsResponse);

            String firstData = "您好，有一份常规报告未完成。";
            String keyWords3 = "在" + stationName + "进行的" + serviceStr + "技术服务，需要" + departmentBuffer + "跟进处理，目前报告状态为" + reportType;
            if (StringUtils.isEmpty(departmentBuffer)) {
                keyWords3 = "在" + stationName + "进行的" + serviceStr + "技术服务，目前报告状态为" + reportType;
            }

            for (User weChatUser : userList) {
                wechatService.pushWechatMessage(weChatUser, "sPL21Oj3MEQjKjGS-GDHQFC_L5Ngiz4zLxsRcYEXAcc", Constants.WECHAT_PUSH_URL, firstData,
                        "请尽快查看并处理", realName, stationReport.getUpdateTimeStr(), keyWords3, "", "");
            }
            logger.info("<<<<<<<<<<<<<<<<<<推送微信成功>>>>>>>>>>>>>>>>>");
            return JsonResponse.successResponse();
        } catch (Exception e) {
            logger.info("<<<<<<<<<<<<<<<<<<发送失败>>>>>>>>>>>>>>>>>!");
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("fail", "发送通知失败");
        }
    }

    @ApiOperation("修改常规报告")
    @RequestMapping(value = "editServiceReport", method = RequestMethod.POST)
    public JsonResponse editServiceReport(@ApiParam("登陆用户ID") @RequestParam(value = "loginUserId") Long loginUserId,
                                          @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId,
                                          @ApiParam("问题ID") @RequestParam(value = "questionId") Long questionId,
                                          @ApiParam("答案ID") @RequestParam(value = "answerId", required = false) String answerId,
                                          @ApiParam("填空") @RequestParam(value = "answerOther", required = false) String answerOther,
                                          @ApiParam("填空2") @RequestParam(value = "answerOther2", required = false) String answerOther2,
                                          @ApiParam("照片") @RequestParam(value = "answerPhoto", required = false) String answerPhoto,
                                          @ApiParam("服务开始时间") @RequestParam(value = "serviceStartTime", required = false) Long serviceStartTime,
                                          @ApiParam("服务结束时间") @RequestParam(value = "serviceEndTime", required = false) Long serviceEndTime,
                                          @ApiParam("跟进部门") @RequestParam(value = "departmentIds", required = false) String departmentIds,
                                          @ApiParam("修改人身份") @RequestParam(value = "userType", required = false) Integer userType,
                                          @ApiParam("管理员确认的备注") @RequestParam(value = "note", required = false) String note) {
        isUserLogin();
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
        if (reportId == null || reportId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "报告ID数据异常");
        }
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null || !stationReport.getCategory().equals(Constants.SERVICE_REPORT)) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该报告或此报告不是常规报告");
        }
        if (questionId == null || questionId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "问题ID数据异常");
        }
        StationRegularServiceReport regularServiceReport = stationRegularServiceReportRepository.selectQuestionOther(reportId, questionId);
        if (regularServiceReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此题答案");
        }
        String originAnswerId = regularServiceReport.getAnswerId();
        String originAnswerOther = regularServiceReport.getAnswerOther();
        //修改手机号码
        if (questionId == 180L) {
            String realName = "";
            String posstion = "";
            StationRegularServiceReport realNameReport = stationRegularServiceReportRepository.selectQuestionOther(reportId, 178L);
            if (realNameReport != null && StringUtils.isNotEmpty(realNameReport.getAnswerOther())) {
                realName = realNameReport.getAnswerOther();
            }
            StationRegularServiceReport positionReport = stationRegularServiceReportRepository.selectQuestionOther(reportId, 179L);
            if (positionReport != null && StringUtils.isNotEmpty(positionReport.getAnswerOther())) {
                posstion = positionReport.getAnswerOther();
            }
            if (regularServiceReport.getAnswerOther().equals(answerOther)) {
                return JsonResponse.errorResponseWithError("", "手机号码一样");
            }
            String telephone = answerOther;
            User stationUser = userRepository.findByUsername(telephone);
            if (stationUser != null) {
                if (stationUser.getUserType().equals(UserType.insiders)) {
                    return JsonResponse.errorResponseWithError("抱歉", "该人员是内部人员无法作为维修站联系人");
                }
                UserProfile stationUserProfile = userProfileRepository.findByUserId(stationUser.getId());
                if (stationUserProfile == null) {
                    return JsonResponse.errorResponseWithError("抱歉", "未找到此联系人具体信息");
                }
                Station addStation = stationReport.getStation();
                if (stationUserProfile.getStationList() != null && stationUserProfile.getStationList().size() > 0) {
                    if (!stationUserProfile.getStationList().contains(addStation)) {
                        stationUserProfile.getStationList().add(addStation);
                        userProfileRepository.save(stationUserProfile);
                        JsonResponse jsonResponse = sendMsg(stationReport, telephone, user);
                        return jsonResponse;
                    }
                } else {
                    List<Station> stationList = new ArrayList<>();
                    stationList.add(addStation);
                    stationUserProfile.setStationList(stationList);
                    userProfileRepository.save(stationUserProfile);
                    JsonResponse jsonResponse = sendMsg(stationReport, telephone, user);
                    return jsonResponse;
                }
            }
            if (stationUser == null) {
                logger.info("<<<<<<<<<<<<<<<<<<开始更新客户账号>>>>>>>>>>>>>>>>>");
                User reportUser = userRepository.findByUserName_phone(regularServiceReport.getAnswerOther());
                reportUser.setUsername(answerOther);
                reportUser.setPassword(passwordEncoder.encode(Constants.INIT_PASSWORD));
                reportUser.setUserType(UserType.customer);
                reportUser.setStationId(stationReport.getStation().getId());
                userRepository.save(reportUser);
                UserProfile reportUserProfile = userProfileRepository.findByUserId(reportUser.getId());
                reportUserProfile.setRealName(realName);
                reportUserProfile.setPosition(posstion);
                reportUserProfile.setTelephone(telephone);
                reportUserProfile.setMobilePhone(telephone);
                reportUserProfile.setUser(reportUser);
                userProfileRepository.save(reportUserProfile);
                regularServiceReport.setAnswerOther(answerOther);
                stationRegularServiceReportRepository.save(regularServiceReport);
                logger.info("<<<<<<<<<<<<<<<<<<新建完毕>>>>>>>>>>>>>>>>>");
                JsonResponse jsonResponse = sendMsg(stationReport, telephone, user);
                if (jsonResponse.isSuccess()) {
                    addEditServiceReportLog(questionId, originAnswerId, answerId, originAnswerOther, answerOther, user, stationReport);
                }
                return jsonResponse;
            }
            return JsonResponse.errorResponseWithError("抱歉", "修改失败");
        }

        //修改联系人名称或者职位
        if ((questionId == 178L || questionId == 179L) && StringUtils.isNotEmpty(answerOther)) {
            StationRegularServiceReport report = stationRegularServiceReportRepository.selectQuestionOther(reportId, questionId);
            if (report != null && StringUtils.isNotEmpty(report.getAnswerOther())) {
                StationRegularServiceReport concatUserReport = stationRegularServiceReportRepository.selectQuestionOther(reportId, 180L);
                User concatUser = userRepository.findByUserName_phone(concatUserReport.getAnswerOther());
                if (concatUser == null) {
                    return JsonResponse.errorResponseWithError("抱歉", "未找到此联系人信息");
                }
                UserProfile userProfile = userProfileRepository.findByUserId(concatUser.getId());
                if (userProfile == null) {
                    return JsonResponse.errorResponseWithError("抱歉", "未找到此联系人信息");
                }
                if (questionId == 178L) {
                    userProfile.setRealName(answerOther);
                } else if (questionId == 179L) {
                    userProfile.setPosition(answerOther);
                }
                report.setAnswerOther(answerOther);
                stationRegularServiceReportRepository.save(report);
                userProfileRepository.save(userProfile);
                addEditServiceReportLog(questionId, originAnswerId, answerId, originAnswerOther, answerOther, user, stationReport);

                return JsonResponse.successResponse();
            } else {
                return JsonResponse.errorResponseWithError("抱歉", "未找到此题答案");
            }
        }

        //修改服务项目
        if (questionId == 155) {
            StationRegularServiceReport report = stationRegularServiceReportRepository.selectQuestionOther(reportId, questionId);
            if (report != null) {
                report.setAnswerId(answerId);
            }
            stationReport.setAnswerOther(answerOther2);
            report.setAnswerOther(answerOther);
            stationReport.setServiceTypAnswerIds(answerId);
            stationReport.setUserType(userType);
            stationReportRepository.save(stationReport);
            stationRegularServiceReportRepository.save(report);
            addEditServiceReportLog(questionId, originAnswerId, answerId, originAnswerOther, answerOther, user, stationReport);

            return JsonResponse.successResponse();
        }

        //修改工作内容以及结果
        if (questionId == 156 && !answerId.equals("182") && StringUtils.isNotEmpty(answerOther)) {
            StationRegularServiceReport report = stationRegularServiceReportRepository.selectQuestionOther(reportId, questionId);
            if (report != null) {
                report.setAnswerId(answerId);
            }
            if (!answerId.equals("182")) {
                stationReport.setDeparmentIds(null);
            }
            report.setAnswerOther(answerOther);
            stationRegularServiceReportRepository.save(report);
            addEditServiceReportLog(questionId, originAnswerId, answerId, originAnswerOther, answerOther, user, stationReport);

            return JsonResponse.successResponse();
        }

        //修改服务开始时间或者服务结束时间
        if ((questionId == 176L || questionId == 177L) && (serviceStartTime != null || serviceEndTime != null)) {
            StationRegularServiceReport report = stationRegularServiceReportRepository.selectQuestionOther(reportId, questionId);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);
            Date date = new Date(Long.valueOf(answerOther));
            String timeStr = simpleDateFormat.format(date);
            report.setAnswerOther(timeStr);
            if (report != null && questionId == 176L) {
                stationReport.setStartServiceTime(date);
            }
            if (report != null && questionId == 177L) {
                stationReport.setEndServiceTime(date);
            }
            stationReportRepository.save(stationReport);
            stationRegularServiceReportRepository.save(report);
            addEditServiceReportLog(questionId, originAnswerId, answerId, originAnswerOther, answerOther, user, stationReport);

            return JsonResponse.successResponse();
        }

        if (questionId == 156L && answerId.equals("182") && StringUtils.isNotEmpty(departmentIds)) {
            StationRegularServiceReport report = stationRegularServiceReportRepository.selectQuestionOther(reportId, questionId);
            report.setAnswerId(answerId);

            String[] serviceTypeIds = stationReport.getServiceTypAnswerIds().split(",");
            StringBuffer stringBuffer = new StringBuffer("");
            for (String id : serviceTypeIds) {
                if (StringUtils.isNotEmpty(id)) {
                    if (id.equals("191")) {
                        stringBuffer.append("漆星服务");
                        break;
                    } else {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                        if (answerOption.getName()!=null&&answerOption.getName()!=null) {
                            stringBuffer.append(answerOption.getName() + ",");
                        }
                    }
                }
            }

            List<Long> oldDepartmentIdList = new ArrayList<>();
            List<Long> newDepartmentIdList = strToList(departmentIds);
            List<Long> newDepartmentIdList1 = strToList(departmentIds);
            User createUser = null;
            UserProfile createUserProfile = null;
            createUser = stationReport.getUser();
            createUserProfile = userProfileRepository.findByUserId(createUser.getId());
            String stationName = "";
            if (StringUtils.isEmpty(stationReport.getDeparmentIds())) {
                stationReport.setDeparmentIds(departmentIds);
            } else {
                oldDepartmentIdList = strToList(stationReport.getDeparmentIds());
                stationName = stationReport.getStation().getName();
                newDepartmentIdList.removeAll(oldDepartmentIdList);
                oldDepartmentIdList.removeAll(newDepartmentIdList1);
                for (Long id : oldDepartmentIdList) {
                    QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
                    BooleanBuilder builder = new BooleanBuilder();
                    builder.and(qReportRedDot.deleted.eq(false));
                    builder.and(qReportRedDot.enabled.eq(true));
                    builder.and(qReportRedDot.departmentId.eq(id));
                    builder.and(qReportRedDot.stationReport.id.eq(reportId));
                    List<ReportRedDot> reportRedDotList = (List<ReportRedDot>) reportRedDotRepository.findAll(builder);
                    for (ReportRedDot redDot : reportRedDotList) {
                        reportRedDotRepository.delete(redDot);
                    }
                }
            }


            List<UserProfile> userProfileList = new ArrayList<>();
            StringBuffer departmentBuffer = new StringBuffer();
            for (Long id : newDepartmentIdList) {
                ReportRedDot redDot = new ReportRedDot();
                redDot.setStationReport(stationReport);
                redDot.setDepartmentId(id);
                redDot.setNote("");
                redDot.setIsSendMsg(0);
                //首次创建部门待处理的话 将报告的创建者设置进去 以便后面区分
                redDot.setUser(createUser);
                redDot.setType(Constants.DEPARTMENT_UNREAD);
                reportRedDotRepository.save(redDot);
                QUserProfile qUserProfile = QUserProfile.userProfile;
                BooleanBuilder builder = new BooleanBuilder();
                builder.and(qUserProfile.deleted.eq(false));
                builder.and(qUserProfile.enabled.eq(true));
                builder.and(qUserProfile.departmentList.any().id.eq(id));
                List<UserProfile> userProfiles = (List<UserProfile>) userProfileRepository.findAll(builder);
                for (UserProfile userProfile : userProfiles) {
                    userProfileList.add(userProfile);
                }

                Department department = departmentRepository.findOne(id);
                if (department != null) {
                    departmentBuffer.append(department.getTotalName() + ",");
                }
            }

            Map<String, Integer> userMap = new HashMap<>();
            for (UserProfile userProfile : userProfileList) {
                String telephone = userProfile.getTelephone();
                if (userMap.containsKey(telephone)) {
                    continue;
                } else {
                    userMap.put(telephone, 1);
                }
            }
            //发送短信通知所选部门下的所有人
            StringBuffer stringBufferUser = new StringBuffer("");
            for (Map.Entry<String, Integer> entry : userMap.entrySet()) {
                String telephone = entry.getKey();
                stringBufferUser.append(telephone + ",");
            }

            Date date = new Date();
            stationReport.setAdminReaded(true);
            stationReport.setUpdateTime(date);
            stationReport.setUpdateTimeStr(new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(date));
            stationReport.setDeparmentIds(departmentIds);
            stationReportRepository.save(stationReport);

            StringBuffer departmentBffer = new StringBuffer("");
            if (StringUtils.isNotEmpty(departmentIds)) {
                String[] ids = departmentIds.split(",");
                for (String id : ids) {
                    if (StringUtils.isNotEmpty(id)) {
                        Department department = departmentRepository.findOne(Long.valueOf(id));
                        if (department != null && StringUtils.isNotEmpty(department.getTotalName())) {
                            departmentBffer.append(department.getTotalName() + ",");
                        }
                    }
                }
            }
            ServiceReportRecorder reportRecorder = new ServiceReportRecorder();
            reportRecorder.setStationReport(stationReport);
            reportRecorder.setNote("确认的部门为：" + departmentBffer.toString());
            reportRecorder.setType(Constants.MANAGE_DEPARTMENT_READ);
            reportRecorder.setUser(user);
            if (StringUtils.isNotEmpty(note)) {
                reportRecorder.setManageNote("备注：" + note);
            }
            serviceReportRecorderRepository.save(reportRecorder);

            ServiceReportHistoricalRecorder serviceReportHistoricalRecorder = new ServiceReportHistoricalRecorder();
            serviceReportHistoricalRecorder.setUser(user);
            serviceReportHistoricalRecorder.setNote("修改了题目");
            serviceReportHistoricalRecorder.setType("修改题目");
            serviceReportHistoricalRecorder.setStationReport(stationReport);
            serviceReportHistoricalRecorderRepository.save(serviceReportHistoricalRecorder);

            try {
                logger.info("发送的手机号码为：" + stringBufferUser);
                logger.info("创建报告者：" + createUserProfile.getRealName());
                logger.info("维修站名称:" + stationName);
                logger.info("服务项目为:" + stringBuffer);
                logger.info("部门为:" + departmentBuffer);
                String serviceStr = stringBuffer.toString();
                if (!serviceStr.equals("漆星服务")) {
                    serviceStr = serviceStr.substring(0, serviceStr.length() - 1);
                }
                String departmentStr = departmentBuffer.toString();
                if (StringUtils.isNotEmpty(departmentBuffer.toString())) {
                    departmentStr = departmentStr.substring(0, departmentBuffer.toString().length() - 1);
                }
                SendSmsResponse sendSmsResponse = aliSmsProvider.sendSureDepartment(stringBufferUser.toString(), createUserProfile.getRealName(), stationName,
                        serviceStr, departmentStr);
                logger.info("发送成功");
                addSendSmsLog(user, createUserProfile.getRealName() + "有一份在" + stationName + "进行" + serviceStr + "的常规服务报告，需要" + departmentStr + "跟进，请尽快登录漆星服务系统进行项目认领跟进。", reportId, sendSmsResponse);
                addEditServiceReportLog(questionId, originAnswerId, answerId, originAnswerOther, answerOther, user, stationReport);
                return JsonResponse.successResponse();
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResponse.errorResponseWithError("抱歉", "发送短信失败");
            }
        }
        //修改
        regularServiceReport.setAnswerId(answerId);
        regularServiceReport.setAnswerOther(answerOther);
        regularServiceReport.setAnswerPhoto(answerPhoto);
        stationRegularServiceReportRepository.save(regularServiceReport);
        addEditServiceReportLog(questionId, originAnswerId, answerId, originAnswerOther, answerOther, user, stationReport);
        return JsonResponse.successResponse();
    }

    public void addEditServiceReportLog(Long questionId, String originAnswerId, String answerId, String originAnswerOther, String answerOther, User user, StationReport stationReport) {
        //        修改日志tom=========================
        try {
            String desc = "";
            Question question = questionRepository.findOne(questionId);
            System.out.println(originAnswerId);
            System.out.println(answerId);
            System.out.println(originAnswerOther);
            System.out.println(answerOther);
            if ((null != answerId && !originAnswerId.equals(answerId)) ||
                    !filterAnswerOther(originAnswerOther).equals(filterAnswerOther(answerOther))) {
                desc += question.getSubject() + ":";
                desc += getAnswerString(originAnswerId) + filterAnswerOther(originAnswerOther) + "-->>" + getAnswerString(answerId) + filterAnswerOther(answerOther) + ",";
            }
            Map<String, Object> data = new HashMap<>();
            data.put("str", desc);
            if (!StringUtils.isEmpty(desc)) {
                String stationNum = "";
                if (null != stationReport.getStation()) {
                    stationNum = stationReport.getStation().getStationNum();
                }
                UserLog userLog = userLogService.addUserLog(user, stationNum, stationReport.getId(), Constants.SERVICE_REPORT, LogConstants.operate_type_edit, LogConstants.business_type_regular_report, null, data);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addSendSmsLog(User user, String desc, Long reportId, SendSmsResponse sendSmsResponse) {
        //        修改日志tom=========================
        if (null != sendSmsResponse && "OK".equals(sendSmsResponse.getCode())) {
            StationReport stationReport = stationReportRepository.findOne(reportId);
            try {
                String stationName = "";
                if (null != stationReport && null != stationReport.getStation()) {
                    stationName = stationReport.getStation().getStationNum();
                }
                Map<String, Object> data = new HashMap<>();
                data.put("str", desc);
                UserLog userLog = userLogService.addUserLog(user, stationName, reportId, Constants.SERVICE_REPORT, LogConstants.operate_type_send_sms, LogConstants.business_type_regular_report, null, data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private List<Long> strToList(String departmentIds) {
        String[] ids = departmentIds.split(",");
        List<Long> idList = new ArrayList<>();
        for (String id : ids) {
            if (StringUtils.isNotEmpty(id)) {
                idList.add(Long.valueOf(id));
            }
        }
        return idList;
    }

    String getAnswerString(String answerIds) {
        List<String> answers = new ArrayList<>();
        List<Long> answerIdArray = ArrayStringUtil.getStringIds(answerIds);
        for (Long answerId : answerIdArray) {
            QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(answerId);
            answers.add(questionAnswerOption.getName());
        }
        return StringUtils.join(answers, ",");
    }

    String filterAnswerOther(String answerOther) {
        try {
            Long currentMin = Long.parseLong(answerOther);
            if (currentMin > 1000000) {
                Date date = new Date(currentMin);
                if (!ValidateUtil.isValidMobileNo(answerOther)) {
                    return DateUtil.formatDate(date, Constants.DATE_FORMAT);
                } else {
                    return AnswerOtherUtil.getOtherString(answerOther);
                }
            } else {
                return AnswerOtherUtil.getOtherString(answerOther);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AnswerOtherUtil.getOtherString(answerOther);
        }
    }


    private JsonResponse sendMsg(StationReport stationReport, String telephone, User loginUser) {
        StringBuffer stringBuffer = new StringBuffer("");
        if (StringUtils.isNotEmpty(stationReport.getServiceTypAnswerIds())) {
            String[] str = stationReport.getServiceTypAnswerIds().split(",");
            for (String s : str) {
                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(s));
                if (answerOption.getId().equals(191L)) {
                    stringBuffer = new StringBuffer("漆星服务");
                    break;
                }
                stringBuffer.append(answerOption.getName());
            }
        }
        String dateTime = stationReport.getUpdateTimeStr();
        User user = stationReport.getUser();
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        String name = userProfile.getRealName();
        Station station = stationReport.getStation();
        String stationName = station.getName();
        String serviceStr = stringBuffer.toString();
        if (!serviceStr.equals("漆星服务")) {
            serviceStr = serviceStr.substring(0, serviceStr.length() - 1);
        }
        try {
            SendSmsResponse sendSmsResponse = aliSmsProvider.sendCustomer(telephone, name, dateTime,
                    stationName, serviceStr);
            addSendSmsLog(loginUser, "AkzoNobel的" + name + "于" + dateTime + "在" + stationName + "进行" + serviceStr + "，请登录漆星服务公众号对Ta的本次服务进行打分", stationReport.getId(), sendSmsResponse);
            logger.info("<<<<<<<<<<<<<<<<<<发送成功>>>>>>>>>>>>>>>>>!");
            return JsonResponse.successResponse();
        } catch (Exception e) {
            logger.info("<<<<<<<<<<<<<<<<<<发送失败>>>>>>>>>>>>>>>>>!");
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("fail", "发送通知失败");
        }
    }


    @ApiOperation("管理员设置的时间，用于定时判断接受之后没有处理的报告")
    @RequestMapping(value = "editTime", method = RequestMethod.POST)
    public JsonResponse editTime(Long userId, Long dayNum) {
        User user = userRepository.findOne(userId);
        AutoMessageTime autoMessageTime = autoMessageTimeRepository.findOne(1L);
        if (autoMessageTime == null) {
            autoMessageTime = new AutoMessageTime();
        }
        autoMessageTime.setUser(user);
        autoMessageTime.setDayNum(dayNum);
        autoMessageTimeRepository.save(autoMessageTime);
        Map<String, Object> data = new HashMap<>();
        data.put("str", dayNum + "天");
        userLogService.addUserLog(this.getCurrentUser(), null, LogConstants.operate_type_set_receive_report, LogConstants.business_type_regular_report, null, data);

        return JsonResponse.successResponse();
    }


}
